package socket

import (
	"bytes"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

func SendLogHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Message string `json:"message"`
		}

		if err := httpx.Parse(r, &req); err != nil {
			httpx.Error(w, err)
			return
		}

		sendLogToLogService(req.Message)

		httpx.Ok(w)
	}
}

func sendLogToLogService(message string) {
	url := "http://localhost:8081/log"
	data := []byte(fmt.Sprintf("message=%s", message))

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		logx.Errorf("Failed to create request: %v", err)
		return
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		logx.Errorf("Failed to send log: %v", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		logx.Errorf("Failed to send log, status code: %d", resp.StatusCode)
	}
}
